﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;

namespace FlyingEye
{
    internal static class WindowsApi
    {
        private static bool? _isWindows7;

        public static bool IsWindows7()
        {
            if (!_isWindows7.HasValue)
            {
                var os = Environment.OSVersion;
                _isWindows7 = os.Platform == PlatformID.Win32NT
                   && os.Version.Major == 6
                   && os.Version.Minor == 1;
            }

            return _isWindows7.Value;
        }

        private const string RunKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Run";

        /// <summary>
        /// 设置应用开机自启
        /// </summary>
        /// <param name="appName">注册表项名称</param>
        /// <param name="exePath">可执行文件完整路径</param>
        public static void SetAutoStart(string appName, string exePath)
        {
            if (string.IsNullOrWhiteSpace(appName) || string.IsNullOrWhiteSpace(exePath))
            {
                throw new ArgumentException("参数不能为空");
            }

            // 标准化路径（处理空格和路径格式）
            var normalizedPath = Path.GetFullPath(exePath.Trim()).TrimEnd('\\');

            // 检查是否需要更新
            if (NeedUpdateAutoStart(appName, normalizedPath))
            {
                UpdateAutoStartRegistry(appName, normalizedPath);
            }
        }

        /// <summary>
        /// 检查是否需要更新注册表项
        /// </summary>
        private static bool NeedUpdateAutoStart(string appName, string exePath)
        {
            try
            {
                using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath);
                if (key == null) return true;

                var currentValue = key.GetValue(appName) as string;
                return currentValue == null ||
                       !string.Equals(currentValue, exePath, StringComparison.OrdinalIgnoreCase);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"检查注册表失败: {ex.Message}");
                return true; // 出错时强制更新
            }
        }

        /// <summary>
        /// 更新注册表项（安全方式）
        /// </summary>
        private static void UpdateAutoStartRegistry(string appName, string exePath)
        {
            try
            {
                // 方法1：直接使用Registry API（推荐）
                using var key = Registry.CurrentUser.CreateSubKey(RunKeyPath);
                key?.SetValue(appName, exePath, RegistryValueKind.String);

                Debug.WriteLine($"已更新开机启动项: {appName} = {exePath}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"更新注册表失败: {ex.Message}");

                // 方法2：备用方案（使用reg.exe）
                TryUpdateWithRegExe(appName, exePath);
            }
        }

        /// <summary>
        /// 备用方案：使用reg.exe命令
        /// </summary>
        private static void TryUpdateWithRegExe(string appName, string exePath)
        {
            try
            {
                var startInfo = new ProcessStartInfo
                {
                    FileName = "reg.exe",
                    Arguments = $"add \"HKEY_CURRENT_USER\\{RunKeyPath}\" " +
                               $"/v \"{appName}\" " +
                               $"/t REG_SZ " +
                               $"/d \"{exePath}\" " +
                               "/f",
                    WindowStyle = ProcessWindowStyle.Hidden,
                    CreateNoWindow = true,
                    UseShellExecute = false
                };

                using var process = Process.Start(startInfo);
                process?.WaitForExit(3000); // 3秒超时

                if (process?.ExitCode != 0)
                {
                    Debug.WriteLine($"reg.exe 执行失败，退出代码: {process?.ExitCode}");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"使用reg.exe更新注册表失败: {ex.Message}");
            }
        }
    }
}